package com.study.hot.rx

import com.blankj.utilcode.util.LogUtils
import com.study.base.BaseActivity
import com.study.hot.R
import com.jakewharton.rxbinding2.view.RxView
import com.jakewharton.rxbinding2.widget.RxCompoundButton
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_rx_binding.*
import java.util.concurrent.TimeUnit

/**
 * <pre>
 *     author : fauks
 *     time   : 2020/03/27
 *     desc   :
 * </pre>
 */
class RxBindingActivity : BaseActivity() {

    //生命周期管理
    private val compositeDisposable: CompositeDisposable by lazy {
        CompositeDisposable()
    }

    override fun generateLayoutId() = R.layout.activity_rx_binding

    override fun initView() {
        super.initView()
        //testRxView()
        //testRxTextView()
        testRxCompoundButton()
    }

    //RxBinding--RxCompoundButton
    private fun testRxCompoundButton() {
        //当选中CheckBox时按钮才可用
        addComposite(RxCompoundButton.checkedChanges(arguCB)
                .subscribe { isChecked ->
                    throttleBtn.isEnabled = isChecked
                    throttleBtn.text = if (isChecked) {
                        "点击"
                    } else "不可点击"
                })
    }

    //RxBinding--RxTextView
    private fun testRxTextView() {
        //限流搜索操作
        addComposite(RxTextView.textChanges(keywordEt)
                .debounce(500, TimeUnit.MILLISECONDS) //限流
                .observeOn(AndroidSchedulers.mainThread())
                .map { c -> c.toString() }  //将EditText的CharSequence转换为String
                .subscribe { keyword -> LogUtils.i("开始搜索$keyword") })
    }

    //RxBinding--RxView
    private fun testRxView() {
        //click防抖动
        addComposite(RxView.clicks(throttleBtn)
                .throttleFirst(3, TimeUnit.SECONDS)  // 设置一段时间内只相应首次或末次时间
                .subscribe {
                    LogUtils.i("click")
                })

        //长按事件
        addComposite(RxView.longClicks(throttleBtn)
                .subscribe {
                    LogUtils.i("long click")
                    //模拟View重绘
                    throttleBtn.viewTreeObserver.dispatchOnDraw()
                })

        //drawable封装onDrawListener当View重绘时触发
        addComposite(RxView.draws(throttleBtn)
                .subscribe {
                    LogUtils.i("view 被重绘")
                })
    }

    //添加订阅
    fun addComposite(disposable: Disposable) {
        compositeDisposable.add(disposable)
    }

    fun clearComposite() {
        compositeDisposable.clear()
    }

    override fun onDestroy() {
        super.onDestroy()
        clearComposite()
    }

}